const http = require('http');
const url = require('url');
const querystring = require('querystring');
const fs = require('fs');

let users = {

}


let server = http.createServer((req, res) => {
  //get
  let { pathname, query } = url.parse(req.url, true);
  console.log('pathname', pathname);
  console.log('query', query);

  //post
  let str = '';
  req.on('data', data => {
    str += data;
  });
  req.on('end', () => {
    let postObj = querystring.parse(str);
    let { user, pass } = query;
    //写东西
    switch (pathname) {
      case '/reg':  //注册

        if (!user) {
          res.write('{ "err": 1, "msg": "username is required" }')
        } else if (!pass) {
          res.write('{ "err": 1, "msg": "pass is required" }')
        } else if (users[user]) {
          res.write('{ "err": 1, "msg": "username repeat" }')
        } else {
          res.write('{ "err": 0, "msg": "success" }')
        }
        res.end()

        break;
      case '/login':  //登陆

        break;

      default:   //其他，文件
        fs.readFile(`www${pathname}`, (err, data) => {
          if (err) {
            res.writeHeader(404)
            res.write('Not Found')

          } else {
            res.write(data)
          }
          res.end()
        })

    }
  })

})

server.listen(9199)